﻿using IBLL;
using IDAL;
using Models;
using Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    /// <summary>
    /// 用户余额表的业务逻辑层
    /// </summary>
    public class UserBalanceInfoBLL : IUserBalanceInfoBLL
    {
        private UnmanContexts _dbContext;
        private IUserBalanceInfoDAL _userBalanceInfoDAL;
        private IUserInfoDAL _userInfoDAL;

        public UserBalanceInfoBLL(
            UnmanContexts dbContext
            , IUserBalanceInfoDAL userBalanceInfoDAL
            , IUserInfoDAL userInfoDAL
            )
        {
            _dbContext = dbContext;
            _userBalanceInfoDAL = userBalanceInfoDAL;
            _userInfoDAL = userInfoDAL;
        }

        #region 根据id获取用户余额详情(GetUserBalanceInfoById)
        /// <summary>
        /// 根据id获取用户余额详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserBalanceInfo GetUserBalanceInfoById(string id)
        {
            return _userBalanceInfoDAL.GetEntityById(id);
        }
        #endregion

        #region 获取余额记录列表的方法(GetBalanceRecordInfo)
        /// <summary>
        ///  获取余额记录列表的方法
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">第几条</param>
        /// <param name="userName">用户余额记录模糊查询条件</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public List<GetBalanceRecordDTO> GetBalanceRecordInfo(int page, int limit, string id, out int count)
        {
            var data = from r in _dbContext.BalanceRecord
                       join b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false)
                       on r.UserbalanceId equals b.Id
                       into tempRB
                       from rb in tempRB.DefaultIfEmpty()

                       join u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       on rb.UserId equals u.Id
                       into tempUrb
                       from urb in tempUrb.DefaultIfEmpty()
                       select new GetBalanceRecordDTO
                       {
                           Id = r.Id,
                           UserbalanceId = rb.Id,
                           Userbalance=rb.Userbalance,
                           Balance = r.Balance,
                           Description = r.Description,
                           Creator = urb.Id,
                           CreateTime = r.CreateTime
                       };
            if (!string.IsNullOrWhiteSpace(id))
            {
                data = data.Where(r => r.Id == id);
            }
            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(r => r.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;
        }
        #endregion

        #region 获取用户余额列表的方法（GetUserBalanceInfo）
        /// <summary>
        ///  获取用户余额列表
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">第几条</param>
        /// <param name="userName">用户余额模糊查询条件</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public List<GetUserBalanceInfosDTO> GetUserBalanceInfo(int page, int limit, string userId, string account, string userName, out int count)
        {
            var data = from b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false)
                       join u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       on b.UserId equals u.Id
                       into tempBU
                       from bb in tempBU.DefaultIfEmpty()

                           //join br in _dbContext.BalanceRecord
                           //on b.Id equals br.UserbalanceId
                           //into TempBR
                           //from bbr in TempBR.DefaultIfEmpty()

                       select new GetUserBalanceInfosDTO
                       {
                           Id = b.Id,
                           Account = bb.Account,
                           Description = b.Description,
                           Userbalance = b.Userbalance,
                           UserName = bb.UserName,
                           UserId = bb.Id,
                           CreateTime = b.CreateTime,
                           //Balance = bbr.Balance
                       };
            //用户姓名不能为空
            if (!string.IsNullOrWhiteSpace(userName))
            {
                data = data.Where(bb => bb.UserName.Contains(userName));
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(userId))
            {
                data = data.Where(bb => bb.UserId == userId);
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(bb => bb.Account == account);
            }
            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(b => b.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;

        }
        #endregion

        #region 获取用户余额列表的方法（GetUserBalanceInfos）
        /// <summary>
        ///  获取用户余额列表
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">第几条</param>
        /// <param name="UserName">用户余额模糊查询条件</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public List<GetUserBalanceInfosDTO> GetUserBalanceInfos(int page, int limit, string userId, string account, string userName, out int count)
        {
            var data = from b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false && b.UserId == userId)
                       join u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       on b.UserId equals u.Id
                       into tempBU
                       from bb in tempBU.DefaultIfEmpty()

                       //join br in _dbContext.BalanceRecord
                       //on b.Id equals br.UserbalanceId
                       //into TempBR
                       //from bbr in TempBR.DefaultIfEmpty()

                       select new GetUserBalanceInfosDTO
                       {
                           Id = b.Id,
                           Account = bb.Account,
                           Description = b.Description,
                           Userbalance = b.Userbalance,
                           UserName = bb.UserName,
                           UserId = bb.Id,
                           CreateTime = b.CreateTime,
                           //Balance = bbr.Balance
                       };
            //用户姓名不能为空
            if (!string.IsNullOrWhiteSpace(userName))
            {
                data = data.Where(bb => bb.UserName.Contains(userName));
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(userId))
            {
                data = data.Where(bb => bb.UserId == userId);
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(bb => bb.Account == account);
            }
            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(b => b.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;

        }
        #endregion

        #region 获取用户余额列表的方法（GetUserBalances）
        /// <summary>
        ///  获取用户余额列表
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">第几条</param>
        /// <param name="UserName">用户余额模糊查询条件</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public List<GetUserBalanceInfosDTO> GetUserBalances(string id, string userId, string account, string userName, out int count)
        {
            var data = from b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false)
                       join u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       on b.UserId equals u.Id
                       into tempBU
                       from bb in tempBU.DefaultIfEmpty()

                       join br in _dbContext.BalanceRecord
                       on b.Id equals br.UserbalanceId
                       into TempBR
                       from bbr in TempBR.DefaultIfEmpty()

                       select new GetUserBalanceInfosDTO
                       {
                           Id = b.Id,
                           Account = bb.Account,
                           Description = b.Description,
                           Userbalance = b.Userbalance,
                           UserName = bb.UserName,
                           UserId = bb.Id,
                           CreateTime = b.CreateTime,
                           Balance = bbr.Balance
                       };
            //用户姓名不能为空
            if (!string.IsNullOrWhiteSpace(userName))
            {
                data = data.Where(bb => bb.UserName.Contains(userName));
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(userId))
            {
                data = data.Where(bb => bb.UserId == userId);
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(bb => bb.Account == account);
            }
            //求总数
            count = data.Count();
            //分页

            var userList = data.OrderByDescending(b => b.CreateTime).ToList();
            //返回结果
            return userList;

        }
        #endregion

        #region 新增用户余额的方法(CreateUserBalanceInfo)
        /// <summary>
        /// 新增用户余额的方法
        /// </summary>
        /// <param name="userBalanceInfo"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CreateUserBalanceInfo(UserBalanceInfo userBalanceInfo, out string msg)
        {
            //非空判断
            if (string.IsNullOrWhiteSpace(userBalanceInfo.UserId))
            {
                msg = "用户Id不能为空！";
                return false;
            }
            if (userBalanceInfo.Userbalance < 0)
            {
                msg = "用户余额不能小于0！!";
                return false;
            }
            //查询判断是否重复
            UserBalanceInfo oldEntity = _userBalanceInfoDAL.GetEntities().FirstOrDefault(u => u.UserId == userBalanceInfo.UserId);
            if (oldEntity != null)
            {
                msg = "该用户id已存在！";
                return false;
            }
            
            //给对象补全属性
            userBalanceInfo.Id = Guid.NewGuid().ToString();
            userBalanceInfo.CreateTime = DateTime.Now;

            //提交到数据库
            bool isSuccess = _userBalanceInfoDAL.CreateEntity(userBalanceInfo);
            //返回结果
            msg = isSuccess ? "添加用户余额成功" : "添加用户余额失败";

            //生产交易记录
            BalanceRecord balanceRecord = new BalanceRecord()
            {
                Id = Guid.NewGuid().ToString(),
                UserbalanceId = userBalanceInfo.Id,
                Balance = Convert.ToInt32(userBalanceInfo.Userbalance),
                Creator = userBalanceInfo.UserId,
                Description = userBalanceInfo.Description,
                CreateTime = DateTime.Now,
            };
            _dbContext.BalanceRecord.Add(balanceRecord);

            bool IsSuccess = _dbContext.SaveChanges() > 0;
            return isSuccess;
        }
        #endregion

        #region 用户下拉列表数据(GetSelectOptions)
        /// <summary>
        /// 用户下拉列表数据
        /// </summary>
        /// <returns></returns>
        public object GetSelectOptions()
        {
            //查用户数据
            var userSelect = _dbContext.UserInfo.Where(m => !m.IsDalete)
                                                        .Select(m => new
                                                        {
                                                            value = m.Id,
                                                            title = m.UserName
                                                        }).ToList();

            //最后返回数据
            var data = new
            {
                userSelect,
            };
            return data;

        }

        #endregion

        #region 编辑用户余额的方法(UpdateUserBalanceInfo)
        /// <summary>
        /// 编辑用户余额的方法
        /// </summary>
        /// <param name=""></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool UpdateUserBalanceInfo(UserBalanceInfo userBalanceInfo, out string msg)
        {
            //非空判断
            if (string.IsNullOrWhiteSpace(userBalanceInfo.Id))
            {
                msg = "用户余额id不能为空";
                return false;
            }
            if (string.IsNullOrWhiteSpace(userBalanceInfo.UserId))
            {
                msg = "用户id不能为空";
                return false;
            }

            //查询旧数据
            UserBalanceInfo oldEntity = _userBalanceInfoDAL.GetEntityById(userBalanceInfo.Id);
            if (oldEntity == null)
            {
                msg = "用户余额不存在!";
                return false;
            }
            if (oldEntity.UserId != userBalanceInfo.UserId)
            {//查找数据库里是否已经有该名字的菜单
                var entity = _userBalanceInfoDAL.GetEntities().FirstOrDefault(c => c.UserId == userBalanceInfo.UserId);
                if (entity != null)
                {
                    msg = "用户余额不是该用户的！!";
                    return false;
                }
            }

            //赋值
            oldEntity.Userbalance = userBalanceInfo.Userbalance;
            oldEntity.Description = userBalanceInfo.Description;
            bool isSuccess = _userBalanceInfoDAL.UpdateEntity(oldEntity);//更新耗材信息到数据库
            msg = isSuccess ? "更新余额成功!" : "更新余额失败!";//返回的信息，三元表达式
            return isSuccess;
        }
        #endregion

        #region 编辑用户余额的方法(UpdateUserBalance)
        /// <summary>
        /// 编辑用户余额的方法
        /// </summary>
        /// <param name=""></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool UpdateUserBalance(UserBalanceInfo userBalanceInfo, int balance, out string msg)
        {

            //非空判断
            if (string.IsNullOrWhiteSpace(userBalanceInfo.Id))
            {
                msg = "用户余额id不能为空";
                return false;
            }
            if (string.IsNullOrWhiteSpace(userBalanceInfo.UserId))
            {
                msg = "用户id不能为空";
                return false;
            }

            //查询旧数据
            UserBalanceInfo oldEntity = _userBalanceInfoDAL.GetEntityById(userBalanceInfo.Id);
            if (oldEntity == null)
            {
                msg = "用户余额不存在!";
                return false;
            }
            if (oldEntity.UserId != userBalanceInfo.UserId)
            {//查找数据库里是否已经有该名字的菜单
                var entity = _userBalanceInfoDAL.GetEntities().FirstOrDefault(c => c.UserId == userBalanceInfo.UserId);
                if (entity != null)
                {
                    msg = "用户余额不是该用户的！!";
                    return false;
                }
            }

            //赋值
            //oldEntity.Userbalance = userBalanceInfo.Userbalance+ balance;
            oldEntity.Userbalance = oldEntity.Userbalance + balance;
            if (oldEntity.Userbalance < 0)
            {
                msg = "用户余额不能小于0！!";
                return false;
            }

            oldEntity.Description = userBalanceInfo.Description;
            bool isSuccess = _userBalanceInfoDAL.UpdateEntity(oldEntity);//更新耗材信息到数据库
            msg = isSuccess ? "更新余额成功!" : "更新余额失败!";//返回的信息，三元表达式

            //生产交易记录
            BalanceRecord balanceRecord = new BalanceRecord()
            {
                Id = Guid.NewGuid().ToString(),
                UserbalanceId = oldEntity.Id,
                Balance = balance,
                Creator = oldEntity.UserId,
                Description = oldEntity.Description,
                CreateTime = DateTime.Now,
            };
            _dbContext.BalanceRecord.Add(balanceRecord);

            bool IsSuccess = _dbContext.SaveChanges() > 0;
            return isSuccess;

        }
        #endregion
    }
}
